﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Collections;

namespace QuickDev.Common.DB
{
    /// <summary>
    /// ReaderFactory
    /// </summary>
    public class ReaderFactory
    {
        /// <summary>
        /// public static void ReaderToModel(T)( IDataReader dr , T model )
        /// </summary>
        /// <typeparam name="T">T</typeparam>
        /// <param name="dr">dr</param>
        /// <param name="model">model</param>
        public static void ReaderToModel<T>( IDataReader dr , T model )
        {
            if ( dr.Read() )
            {
                for ( int i = 0 ; i < dr.FieldCount ; i++ )
                {
                    System.Reflection.PropertyInfo propertyInfo = model.GetType().GetProperty( dr.GetName( i ) );
                    if ( propertyInfo != null )
                    {
                        if ( dr.GetValue( i ) != DBNull.Value )
                        {
                            propertyInfo.SetValue( model , Convert.ChangeType( dr.GetValue( i ) , dr.GetValue( i ).GetType() ) , null );
                        }
                    }
                }
            }

            dr.Close();
        }

        /// <summary>
        /// public static void ReaderToList(T)( IDataReader dr , List<T> modelList )
        /// </summary>
        /// <typeparam name="T">T</typeparam>
        /// <param name="dr">dr</param>
        /// <param name="modelList">modelList</param>
        public static void ReaderToList<T>( IDataReader dr , List<T> modelList )
        {
            while ( dr.Read() )
            {
                T model = System.Activator.CreateInstance<T>();

                for ( int i = 0 ; i < dr.FieldCount ; i++ )
                {
                    System.Reflection.PropertyInfo propertyInfo = model.GetType().GetProperty( dr.GetName( i ) );
                    if ( propertyInfo != null )
                    {
                        if ( dr.GetValue( i ) != DBNull.Value )
                        {
                            propertyInfo.SetValue( model , Convert.ChangeType( dr.GetValue( i ) , dr.GetValue( i ).GetType() ) , null );
                        }
                    }
                }

                modelList.Add( model );
            }

            dr.Close();
        }
    }
}
